import path from "path";
import fs from "fs";

interface OptionFace {
  file: any;
  pathUrl?: string;
  pathName?: string;
  name?: string;
}

export default class extends think.Service {
  async upload(option: OptionFace) {
    return new Promise((resolve, reject) => {
      const { file, pathUrl } = option;
      let { pathName, name } = option;
      let allPath: string;
      if (pathUrl) {
        allPath = think.ROOT_PATH + "/www/static" + pathUrl;
      } else {
      }

      var dirname = path.dirname(allPath); // 获取文件的目录
      const isAccess = fs.existsSync(dirname); // 判断是否存在目录
      if (!isAccess) {
        fs.mkdirSync(dirname, { recursive: true }); // 自动创建多层目录  recursive:true 多层
      }

      const is = file.path ? fs.createReadStream(file.path) : file;
      const os = fs.createWriteStream(allPath);
      is.pipe(os);

      os.on("finish", () => {
        resolve({
          url: pathUrl,
          baseUrl: process.env.BASE_IMG_URL + pathUrl,
        });
      });
      os.on("error", reject);
    });
  }
  async uploadFile(option: OptionFace1) {
    const { file } = option;
    const ext = path.extname(file.name);

    let { pathName, name } = option;
    return new Promise((resolve, reject) => {
      if (pathName) {
        pathName = "/" + pathName.replace(/^(\/)/, "");
      } else {
        pathName = `/upload/`;
      }
      if (name) {
        name = name.replace(/^(\/)?|(\/)$/g, "");
      } else {
        name = think.uuid("32") + ext;
      }
      const filename = pathName + name;
      let fileData = typeof file.path == "string" ? file : file.path;
      const is = fs.createReadStream(fileData);
      const os = fs.createWriteStream(think.ROOT_PATH + "/www" + filename);
      is.pipe(os);
      os.on("finish", () => {
        resolve({
          url: filename,
          baseUrl: process.env.BASE_IMG_URL + filename,
        });
      });
      os.on("error", reject);
    });
  }

  async uploadAiImg(file: File) {
    const pathUrl = "/images/aiimg/" + think.uuid("32") + ".png";

    return await this.upload({
      file,
      pathUrl,
    });
  }
  async uploadAiUserImg(file: File) {
    console.log(file);

    //const ext = path.extname(file.name);
    const pathUrl = "/images/aiimgUser/" + think.uuid("32") + ".jpg";

    return await this.upload({
      file,
      pathUrl,
    });
  }
}
